<?php

declare(strict_types=1);

namespace App\Middleware;

use App\Constants\ContextKey;
use App\Constants\ErrorCode;
use App\Exception\BusinessException;
use App\Model\User;
use App\Utils\Jwt;

use Hyperf\Utils\Context;
use Psr\Container\ContainerInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;

class ClientAuthMiddleware implements MiddlewareInterface
{
    /**
     * @var ContainerInterface
     */
    protected $container;


    public function __construct(ContainerInterface $container)
    {
        $this->container = $container;
    }

    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        if (!$request->hasHeader('authorization')) {
            throw new BusinessException(ErrorCode::UNAUTHORIZED);
        }

        $token = $request->getHeaderLine('authorization');

        $verifiedToken = Jwt::verify($token);
        $user_id = $verifiedToken->getClaim('user_id');

        /** @var User $userInfo */
        $userInfo = User::query()
            ->where(['id' => $user_id])
            ->first();
        if (!$userInfo) {
            throw new BusinessException(ErrorCode::USER_NOT_EXIST);
        }
        Context::set(ContextKey::USER, $userInfo);
        return $handler->handle($request);
    }

}